import {useState} from 'react';
import {ToastManger} from '../components/Toast';

type GetResult<T> = T extends (params?: any) => Promise<infer U> ? U : any;

export function useFetch<
  Request extends (...params: any[]) => Promise<any>,
  K extends GetResult<Request> | undefined,
>(api: Request, defaultValue?: K) {
  const [loading, setLoading] = useState(false);

  const [state, setState] = useState<GetResult<Request> | undefined>(
    defaultValue,
  );

  const getValue = async (...params: Parameters<Request>) => {
    setLoading(true);

    try {
      const result = await api(...params);
      setState(result);
    } catch (error) {
      ToastManger.displayAlert({
        // @ts-ignore
        message: error?.cnmsg || '网络连接超时，请点击重试 或切换网络重试。',
      });
    }
    setLoading(false);
  };

  return [
    state as K extends undefined
      ? GetResult<Request> | undefined
      : GetResult<Request>,
    getValue,
    loading,
  ] as const;
}

// interface NetRes<T = any> {
//   enmsg: string;
//   cnmsg: string;
//   data: T;
//   code: number;
// }
/** 不管是正确还是错误，将数据处理成同样返回格式的数据， */
// function post<T>(url: string, params: any = {}) {
//   const headers = new Headers({
//     'Content-Type': 'application/json',
//   });

//   const body = JSON.stringify(params);

//   /** 需要接受 返回的值 */
//   return fetch(url, {
//     headers,
//     body,
//     credentials: 'same-origin',
//   })
//     .catch(e => {
//       const data = handleError(e);
//       // throw new Error(data);
//       return Promise.reject(data);
//     })
//     .then(res => res.json())
//     .then((resp: NetRes<T>) => {
//       if (resp.code === 200 && resp.cnmsg === 'ok') {
//         // return Promise.resolve(resp);
//         return resp;
//       } else {
//         return Promise.reject(resp);
//       }
//     });
// }

// const handleError = (err: Error): NetRes<null> => {
//   let message: string = err.message;

//   switch (err.message) {
//     case 'xxx':
//       message = 'xxxxx';
//       break;
//   }
//   return {
//     cnmsg: err.message,
//     enmsg: message,
//     code: 500,
//     data: null,
//   };
// };
